package com.study.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.HttpResource;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.study.model.pojo.Dept;
import com.study.services.CollectionService;
import com.study.services.CusmshfitServices;
import com.study.services.CustomerService;
import com.study.services.DeptService;
import com.study.services.PermissionServices;
import com.study.services.RoleService;
import com.study.services.UserService;

@Controller
public class UserController {
	@Autowired
	UserService uService;
	@Autowired
	DeptService deptService;
	@Autowired
	RoleService roleService;
	@Autowired
	CusmshfitServices cusms;
	@Autowired
	CustomerService cust;
	@Autowired
	PermissionServices permssion;
	String[] xms= {};
	List<String> rolise;
	String img; 
	@RequestMapping(value="/dept")

	public ModelAndView getCusmshiAll(){
		ModelAndView mv=new ModelAndView("/permission/dept");
	
		//JSONArray getfindDept = deptService.getfindDept();
		//List<JSONObject> findDeptAll = deptService.getFindDeptAll();
		
		//mv.addObject("piliang",getfindDept);
		//deptService.getfindDept();
	//	deptService.getFindUsersDeptId(2);
		//deptService.getFindTreeDept();
		return mv;
	} 

	
/*	*//**
	 * 查询所有部门
	 * @return 
	 */
	@PostMapping("usercontroner/selectdeptall")
	@ResponseBody
	public List<JSONObject> getFindDeptAll(){
		List<JSONObject> findDeptAll = deptService.getFindDeptAll();
		for (JSONObject jsonObject : findDeptAll) {
			System.out.println("xmmdsdsdd哈哈哈哈哈        "+jsonObject);
		}
		return findDeptAll;
	}
	
	@PostMapping("/selectdept.do")
	@ResponseBody
	public JSONArray getFindDept(){
		/*List<JSONObject> findDeptAll = deptService.getFindDeptAll();
		for (JSONObject jsonObject : findDeptAll) {
			System.out.println("xmmdsdsdd哈哈哈哈哈        "+jsonObject);
		}*/
		//JSONArray findDeptUserAll = deptService.getFindTreeDept();
		JSONArray findDeptUserAll = deptService.getFindTreeDept();
		//JSONArray findDeptUserAll=deptService.getFindDeptse();
		return findDeptUserAll;
	}
	
	/**
	 * 跳转到用户添加页面
	 * @return
	 */
	@RequestMapping(value="/adduser")
	public ModelAndView setaddUser(String use){
		List<JSONObject> findDeptRole= deptService.findDeptRoleNmae(use);
		System.out.println(use +"     use");
		ModelAndView mv=new ModelAndView("/permission/adduser");
		mv.addObject("piliang",findDeptRole);	
		for (JSONObject jsonObject : findDeptRole) {
			System.out.println("jsonObject          "+jsonObject);
		}
		return mv;
	} 
	
	/**
	 * 跳转到权限页面
	 * @return
	 */
	@RequestMapping(value="/userpermission")
	public ModelAndView setPermissionUser(HttpServletRequest request){	
		ModelAndView mv=new ModelAndView("/permission/userpermission");		
		 JSONArray ect=new JSONArray();
		 Set<String> sts=new HashSet<>();
		 List<JSONObject> getfidnPerstionroleid = permssion.getfindRolePeAll();
		mv.addObject("ect",getfidnPerstionroleid);
		for (JSONObject json : getfidnPerstionroleid) {
			 sts.add(json.getString("rol_name"));
		}
		for (String strsr : sts) {
			String st="";
			 JSONObject obj=new JSONObject();
			for (JSONObject jsonObject : getfidnPerstionroleid) {
				if(strsr.equals(jsonObject.getString("rol_name"))) {
					st=st+"、"+jsonObject.getString("per_name");
					obj.put("rol_id", jsonObject.getString("rol_id"));
				}
			}
			obj.put("rol_name",strsr);
			obj.put("per_name",st.substring(1, st.length()));
				ect.add(obj);
		}
		mv.addObject("sts",ect);
		//mv.addObject("piliang",findDeptRole);	
	    //获取所有的员工部门信息
		JSONArray getfindDept = deptService.getFindTreeDept();
			mv.addObject("piliang",getfindDept);
		return mv;
	} 
	
	
	
	
	
	/**
	 * 添加用户信息
	 * @param username
	 * @param userphone
	 * @param role
	 * @param dept
	 * @param useid
	 * @return 
	 */
	@PostMapping("setUseradd")
	@ResponseBody
    public JSONObject setformUser(@RequestParam("username")String username,
    		@RequestParam("userphone")String  userphone,
    		@RequestParam("password")String  password,
    		@RequestParam("age")String  age,
    		@RequestParam("role")Object role,
    		@RequestParam("sex")Object sex,
    		@RequestParam("deptid")Object dept,@RequestParam("loginname")String loginname){
		 System.out.println(username+"\t"+userphone+"\t"+role+"\t"+dept+"\t"+age+"\t"+loginname+"\t"+password);
		JSONObject obj=new JSONObject();
		 JSONObject findUserLogname = uService.getFindUserLogname(loginname);
		System.out.println(findUserLogname);
		/* Object object = findUserLogname.get(loginname);
		 String ste=findUserLogname.getString("use_id");*/
		 //判断登录是否存在
		 if(findUserLogname==null) {
			 uService.setUserAdd(username, password,(String)sex,userphone,loginname,img,Integer.parseInt(age));
			 int parseInt = Integer.parseInt(uService.getFindUserLogname(loginname).getString("use_id"));
			 System.out.println(parseInt);
			 //实现用户和部门绑定
			 uService.setUserDept(parseInt, Integer.parseInt(dept.toString()));
			 //实现用户和角色绑定
			 uService.setUserRole(parseInt, Integer.parseInt(role.toString()));
			 obj.put("usetype", "添加成功");
			 System.out.println("添加成功");
		 }else {
			 obj.put("usetype", "存在相同的登录名");
			 System.out.println("存在相同的登录名");
		 }
		 return obj;
    }
	
	
	/**
	 * 文件上传Wcx
	 */
	@PostMapping("/userwjlfile")
	public ModelAndView upload(MultipartFile file,
					   HttpServletRequest request,HttpSession session){
		//file存储了上传的文件的所有信息
		ModelAndView mv = new ModelAndView("permission/adduser");
		try {
			
			System.out.println(file+"                      filsessss");
			//转存到指定目录
			//1、获取当前工程发布所在的物理路径，文件上传目录WebContent/upload
			ServletContext context = request.getServletContext();
			System.out.println("context     :"+context);
			//2、全球唯一码作为新的文件名
			String newname = UUID.randomUUID().toString().toUpperCase();
			//3、获取源文件的后缀名（png）
			String suffix = "."+FilenameUtils.getExtension(file.getOriginalFilename());
			//4、创建新文件（存储在硬盘上，使用物理路径。）
			//File new_file=new File("G:\\git\\CRM\\src\\main\\resources\\static\\gimg"+"/"+newname+suffix);
			//D:\\Users\wjl\git\CRM
			File new_file=new File("D:\\Users\\wjl\\git\\CRM\\src\\main\\resources\\static\\images\\imgwjl"+"/"+newname+suffix);
			System.out.println("new_file========:"+new_file);
			 img = "/images/imgwjl/"+newname+suffix;
			System.out.println("拼接的图片路径======："+img);
			
			JSONObject object = new JSONObject();
			object.put("img", object);
			session.setAttribute("img", img);
			//5、将源文件转存到新文件上
			file.transferTo(new_file);
              mv.addObject("1","13456") ;
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} 
		catch (IOException e) {
			e.printStackTrace();
		}
		return mv;
	}
	
	/*@GetMapping("/selectdept.do")
	public List<Dept> getFindDept(){
		List<Dept> findDeptAll = deptService.getFindDeptAllse();
		for (Dept jsonObject : findDeptAll) {
			System.out.println(jsonObject.toString());
		}
		ModelAndView mvAndView=new ModelAndView("/customer/dept");
		mvAndView.addObject("dept", findDeptAll);
		return findDeptAll;
	}*/
	
	
	/**
     * 保存节点
	 * @return 
     */
    @RequestMapping("/saveTreeNode.do")
    @ResponseBody
    public JSONObject saveTreeNode(@RequestParam("depName")String depName,
    		@RequestParam("supperdepName")String supperdepName){
       // System.out.println(depName +"------" +dep_id);
        //根据父级部门名称查询父级部门信息
        List<JSONObject> findDeptNmae = deptService.findDeptNmae(supperdepName);
        Dept dept=new Dept();
        dept.setDepName(depName);
        JSONObject obj=new JSONObject();
        String depid="";
        for (JSONObject jsonObject : findDeptNmae) {
        	//添加子级部门父级id
        	  dept.setDepSuperid(Integer.parseInt(jsonObject.getString("dep_id")));
        	  depid=jsonObject.getString("dep_id");
		}
      //添加子级部门
        String settyoe =deptService.setInsertDept2(dept);
        //根据父级部门id查询对应角色，实现子级部门继承父级部门角色
        List<JSONObject> findrole = deptService.getFindrole(depid);
        List<JSONObject> findDeptsonNmae = deptService.findDeptNmae(depName);
        for (JSONObject deptidas : findDeptsonNmae) {
        	for (JSONObject roleide : findrole) {
        		//实现部门和角色的绑定
        		deptService.setfundeptrole(deptidas.getString("dep_id"),roleide.getString("rol_id"));
    		}
		}
        obj.put("settype", settyoe);
        return obj;
    }

    /**
     *   查询所有父级部门都是公司的部门
     * @param supperid
     * @return 
     */
    @GetMapping("/updatedpt")
   public ModelAndView getfinddeptsuperid(@RequestParam("depName") String deptname) {
	   JSONObject obj=new JSONObject();
	   System.out.println("xmxxxmxmxxmm            "+deptname);
	   List<JSONObject> findDeptSupperid = deptService.getFindDeptSupperid("7");
	   ModelAndView mv=new ModelAndView("permission/updatedept");
	   mv.addObject("findDeptSupperid", findDeptSupperid);
	   return mv;
   }
    
    
    @RequestMapping("/deleTreeNode.do")
    @ResponseBody
    public JSONObject deleTreeNode(@RequestParam("val") String val){
        System.out.println(val+"                  strse");
        List<JSONObject> getfindDepets = deptService.getfindDepets(val);
       JSONObject selectDeptname = deptService.selectDeptname(val);
       System.out.println(selectDeptname.getString("dep_superid")+"    dep_superid");
       List<JSONObject> findDeptByPar = deptService.findDeptByPar(Integer.parseInt(selectDeptname.getString("dep_id")));
        JSONObject obj=new JSONObject();
        if(getfindDepets.size()>0||findDeptByPar.size()>0) {
        	if(getfindDepets.size()>0) {
        		obj.put("xm", "该部门下存在用户不能删除");
        		System.out.println("xxmxm该部门下存在用户不能删除");
        	}else {
        		obj.put("xm", "该部门下存在子级部门不能删除");
        		System.out.println("xxmxm该部门下存在子级部门不能删除");
        	}        	
        }else {
        	deptService.delectDeptrole(selectDeptname.getInteger("dep_id"));
        	deptService.setDelectDept(selectDeptname.getInteger("dep_id"));
        	System.out.println("xxmxm删除成功");
        	obj.put("xm", "删除成功");
        }
       /* for (JSONObject jsonObject : getfindDepets) { 
			
		}*/
     /*   String [] strIds = val.substring(1,val.length()-1).split(",");
        System.out.println(strIds.toString()+"              sifsfsfsfs");*/
       /* for(int i =0;i<strIds.length;i++){
        	deptService.setDelectDept(Long.valueOf(strIds[i])); // 1,2
        }*/
        return obj;
    }
	
	/**
	 * 查看修改用户详情
	 * @param linid
	 * @return
	 */
	@GetMapping("updateusers")
	public ModelAndView updatelinkman(Integer id){
		System.out.println("进来了");
		System.out.println(id);
		int linid=id.intValue();
		ModelAndView mv = new ModelAndView("permission/userxiangqing");
		JSONObject jsonObject =uService.getFindUserRoleDept(linid);
		
		List<JSONObject> findDeptAll = deptService.getFindDeptAll();
		List<JSONObject> findRoleAll = roleService.getFindRoleAll();		
		//加入所有部门信息用于用户修改
		jsonObject.put("deptallname", findDeptAll);
		//加入所有角色信息用于用户修改
		jsonObject.put("roleallname", findRoleAll);
		System.out.println(jsonObject.getString("deptallname"));
		System.out.println(jsonObject.getString("deptallname"));
		System.out.println(jsonObject+"           jsonObject");
		mv.addObject("linkmanaaa",jsonObject); 
		return mv;		
	}
    
	
	
	
	/**
	 * 修改用户信息
	 * @param username
	 * @param userphone
	 * @param role
	 * @param dept
	 * @param useid
	 */
	@PostMapping("setRefromUser")
    public void setRefromUser(@RequestParam("username")String username,
    		@RequestParam("userphone")String  userphone,
    		@RequestParam("loginname")String  loginname,
    		@RequestParam("role")Object role,
    		@RequestParam("dept")Object dept,@RequestParam("useid")int useid){    	
		 System.out.println(username+"\t"+userphone+"\t"+role+"\t"+dept+"\t"+useid);
		 try{
			 uService.setUpdateDeptUserId(Integer.parseInt(dept+""), useid);
		  }catch(NumberFormatException e)
		  {
			  List<JSONObject> findDeptNmae = deptService.findDeptNmae(dept+"");
			  for (JSONObject jsonObject : findDeptNmae) {
				  uService.setUpdateDeptUserId(Integer.parseInt(jsonObject.getString("dep_id")), useid);
			}
		  }		 
		 try{
			 uService.setUpdateRoelUserid(Integer.parseInt(role+""), useid);
		  }catch(NumberFormatException e)
		  {
			  List<JSONObject> findDeptNmae =roleService.getFindRoleName(role+"");
			  for (JSONObject jsonObject : findDeptNmae) {
				  uService.setUpdateDeptUserId(Integer.parseInt(jsonObject.getString("rol_id")), useid);
			}
		  }
		 //uService.setUpdateRoelUserid(Integer.parseInt(role+""), useid);
		  uService.setUpdateUserId(username, userphone, useid,loginname);
		  
    }	
	/**
	 * 查询所有用户的角色和用户信息
	 * @return 
	 */
	@PostMapping("selectuserroleall")
	@ResponseBody
	public List<JSONObject> getFindUserRoleAll() {
		List<JSONObject> findUserRolessee = uService.getFindUserRolessee();
		for (JSONObject jsonObject : findUserRolessee) {
			System.out.println(jsonObject+"                   用户角色信息");
		}
		return findUserRolessee;
	}
	
	
	/**
	 * 查找所有用户
	 * @return 
	 */
	@PostMapping("/selectcustuser")
	 @ResponseBody
	public List<JSONObject> getFindKehu() {
		List<JSONObject> findUserAll = uService.getFindUserAll();
		for (JSONObject jsonObject : findUserAll) {
			System.out.println(jsonObject);
		}
		return findUserAll;
	}
	
	/**
	 * 实现添加分享记录
	 * @param array
	 * @return 
	 * @throws IOException 
	 */
	@RequestMapping(value = "/selsefrom", method = {RequestMethod.POST})
	public void setKehuzhuangyi(@RequestBody String[] array,HttpServletResponse response) throws IOException {
		int addCusm=0;
		PrintWriter writer= response.getWriter();
		for (String cusid : xms) {			
			System.out.println(cusid+"             客户记录");
			JSONObject selectcusid = cust.selectBycusid(Integer.parseInt(cusid));
			for (String string : array) {
			//	System.out.println(string+"     xmmxxmmxmx");
				String[] split = string.split(",");
			System.out.println(split[0]+"          "+split[1]);
			
			//修改语句
			//应该判断分享者是否存在相似的权限，如果存在则修改权限而不是添加记录
				List<JSONObject> cusmsh= cusms.cusmshfitIDall(Integer.parseInt(selectcusid.getString("user_id")),+ 
						Integer.parseInt(split[0]),Integer.parseInt(selectcusid.getString("cus_id")));
				if(cusmsh.size()<=0) {
					addCusm = cusms.addCusm(4,Integer.parseInt(selectcusid.getString("user_id")),
							Integer.parseInt(split[0]),Integer.parseInt(selectcusid.getString("cus_id")), split[1]);
				}else {
					//writer.println();
					cusms.updateCusm(4,Integer.parseInt(selectcusid.getString("user_id")),
							Integer.parseInt(split[0]),
							Integer.parseInt(selectcusid.getString("cus_id")),
							split[1]);
					System.out.println("存在相同分享记录，将不会重复添加");
					addCusm=2;
				}
			}						
		}			
		System.out.println(addCusm);
	}
	/**
	 * 获取要被分享的客户数据
	 * @param array
	 */
	@RequestMapping(value = "/selsekehu", method = {RequestMethod.POST})
	public void getkehufenxiang(@RequestParam("type[]")String[] array) {
		System.out.println(array);
		xms=array;
		for (String string : array) {
			System.out.println(string+"     客户数据");			
		}
	}
	
	/**
	 * 
	 */
	@PostMapping("/afterSale/queryUser")
	@ResponseBody
	public List<JSONObject> getUser(String depid){
		List<JSONObject> users = deptService.findUserBydepid(depid);
		return users;
	}
	
	/**
	 * 实现带参跳转到添加角色界面
	 * @return
	 */
	 @RequestMapping(value="/addrole")
	    public ModelAndView getFindRolePerssion() {
		 //获取部门
		 List<JSONObject> findDeptAll = deptService.getFindDeptAll();
		 //获取权限
		 List<JSONObject> findPersstion = permssion.getFindPersstion();
		 ModelAndView mv=new ModelAndView("/permission/addrole");
		 JSONObject obj=new JSONObject();
		 obj.put("deptse", findDeptAll);
		 obj.put("persstion", findPersstion);
		mv.addObject("xms", obj);
		 return mv;
	    }
	 
	 /**
	  * 实习角色的添加
	  */
	 @PostMapping("setRole")
	 public void setRoleperssmtion(@RequestParam("dep_id")String dep_id,
			 @RequestParam("roleName")String roleName,@RequestParam("permissionrole[]")String[] permissionrole) {
		 System.out.println(dep_id+"          "+roleName+"       "+permissionrole.toString());
		 //添加角色
		 roleService.setRole(roleName);
		 //根据角色查找角色id
		 List<JSONObject> findDeptNmae =roleService.getFindRoleName(roleName+"");
		  for (JSONObject jsonObject : findDeptNmae) {
			  //实现部门和角色绑定
			 deptService.setfundeptrole(dep_id,jsonObject.getString("rol_id"));
			 for (int i = 0; i < permissionrole.length; i++) {
				 //实现角色和权限绑定
				roleService.setrolePersstion(jsonObject.getString("rol_id"), permissionrole[i]);
			}
		}
		  
	 }
	 
	 /**
	  * 查询该角色对应的权限
	  * @param request
	 * @return 
	  */
	 @PostMapping("persstiionrole")
	 public JSONObject getFindRoleperstion(HttpServletRequest request) {
		 JSONObject ect=new JSONObject();
		 List<String> attribute = (List<String>) request.getSession().getAttribute("roleid");
		 for (String string : attribute) {
			 JSONObject obj=new JSONObject();
			 //获取对应的权限
			 List<JSONObject> getfidnPerstionroleid = permssion.getfidnPerstionroleid(string);
			 obj.put("roelperstion", getfidnPerstionroleid);
			 ect.put("ect", obj);
		}
		return ect;
	 }
	 @GetMapping("/userrole")
	 public ModelAndView getFindRoleiduse(@RequestParam("rolid")int rolid) {
		 List<JSONObject> findRoleUser = uService.getFindRoleUser(rolid);
		 rolise=new ArrayList<>();
		 ModelAndView mv=new ModelAndView("/permission/addusermissionweixiu");
		 List<JSONObject> obj = new ArrayList<>();
		 for (JSONObject jsonObject : findRoleUser) {
			 JSONObject objse = new JSONObject();
			 objse.put("label", jsonObject.getString("use_name"));
				objse.put("value", jsonObject.getString("use_id"));
				//保存该角色下的用户id
				rolise.add(jsonObject.getString("use_id"));
				obj.add(objse);
		}
		 mv.addObject("roidss", rolid);
		 mv.addObject("roluse", obj);
		 return mv;
	 }
	 /**
	  * 实现修改角色下对应的用户操作
	  * @param value5
	  * @param roleid
	  */
	 @RequestMapping(value = "/setUserRolett", method = { RequestMethod.POST })
	  public void setUserRole(@RequestParam("values[]") String[] value5,@RequestParam("roleid") String roleid) {
		 Set<String> str=new HashSet<>();
		  for (int i = 0; i < value5.length; i++) {
			  System.out.println("valuse5         "+value5[i]);
			  str.add(value5[i]);			
		}
		  for (String string : str) {
			  uService.setDelectUserRole(Integer.parseInt(string), Integer.parseInt(roleid));
		}
		  
		 /* for (String string : str) {
			  for (String string : rolise) {
					System.out.println("string        "+string);
					if(!value5[i].equals(string)) {
						//实现解除用户和角色的绑定
						uService.setDelectUserRole(Integer.parseInt(string), Integer.parseInt(roleid));
						System.out.println("xmxmxmxxx           "+string);
					}
				}
			}*/
		  
	  }
	 
	 @PostMapping("/delectrole")
	 @ResponseBody
	 public JSONObject delectrole(@RequestParam("rolid") String rolid) {
		 System.out.println(rolid+"          rolidsflsf's");
		 List<JSONObject> findRoleUser = uService.getFindRoleUser(Integer.parseInt(rolid));
		 for (JSONObject jsonObject : findRoleUser) {
			System.out.println(jsonObject);
		} 
		 JSONObject obj=new JSONObject();
		 if(findRoleUser.size()>0) {
			 obj.put("xm", "该角色下存在用户，不能删除");
			 System.out.println("该角色下存在用户，不能删除");
		 }else {
			 int delectrolidperstion = roleService.delectrolidperstion(rolid);
			 int delectrolid = roleService.delectrolid(rolid);
			 System.out.println("delectrolidperstion+"+delectrolidperstion);
			 System.out.println("delectrolid+"+delectrolid);
			 obj.put("xm", "删除成功");
			 System.out.println("删除成功");
		 }
		 return obj;
	 }
	 
	 @PostMapping("/selectuserdepos")
	 @ResponseBody
	 public JSONObject getfinduseriddept(HttpServletRequest request) {
		 String useid = request.getSession().getAttribute("useid").toString();
		 JSONObject getfindUseriddept = uService.getfindUseriddept(useid);
		 System.out.println(getfindUseriddept);
		 return getfindUseriddept;
	 }
	 
}
